﻿using System;

namespace JQuery.WebKit.WebCommon.Javascript
{
    public static class Utils
    {
        #region public static string ToJSString(this object objectInstance)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectInstance"></param>
        /// <returns></returns>
        
        public static string ToJSString(this object objectInstance)
        {
            return ToJSString(objectInstance, string.Empty);
        }
        #endregion

        #region public static string ToJSString(this object objectInstance, string removeValue)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objectInstance"></param>
        /// <param name="removeValue"></param>
        /// <returns></returns>
        public static string ToJSString(this object objectInstance, string removeValue)
        {
            if (objectInstance == null)
            {
                return "null";
            }
            string strVal = string.Empty;
            switch (objectInstance.GetType().ToString())
            {
                case "System.String":
                    string oStr = objectInstance.ToString().Replace("'", "\"").Trim();
                    if ((oStr[0] == '{' && oStr[oStr.Length - 1] == '}') || (oStr.StartsWith("function")))
                    {
                        strVal = oStr;
                    }
                    else
                    {
                        strVal = "'" + oStr + "'";
                    }
                    break;
                case "System.Boolean":
                    strVal = objectInstance.ToString().ToLower();
                    break;
                case "System.Web.UI.WebControls.Unit":
                    strVal = objectInstance.ToString().ToLower().Replace("px", "");
                    break;
                case "System.Enum":
                    strVal = "'" + objectInstance.ToString() + "'";
                    break;
                default:
                    strVal = objectInstance.ToString();
                    break;
            }
            if (!string.IsNullOrEmpty(removeValue))
            {
                strVal = strVal.Replace(removeValue, string.Empty);
            }
            if (objectInstance is Enum)
            {
                strVal = string.Format("'{0}'", strVal);
            }
            return strVal;
        }
        #endregion

    }
}
